<?php

namespace App\Http\Controllers\admin;
use App\Models\Company\CrmService;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Style,View,DB;

class WorkerHandleController  extends Controller
{
    /**
     * 员工列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request){
        $keyword = $request->keyword;
        $userList = CrmService::select('uid', 'name', 'worker_name', 'email', 'mobile', 'phone')
            ->where(function ($query) use ($keyword) {
                if (strlen($keyword) > 0) {
                    $query->orWhere('uid', '=', $keyword)
                        ->orWhere('name', 'like', '%' . $keyword . '%')
                        ->orWhere('worker_name', 'like', '%' . $keyword . '%')
                        ->orWhere('phone', 'like', '%' . $keyword . '%')
                        ->orWhere('mobile', 'like', '%' . $keyword . '%');
                }
            })
            ->paginate(20);
        $display_name = [];
        foreach($userList as $v){
            $v->mobile =='' ? $v->mobile = '未填写手机' : '';
            $v->phone =='' ? $v->phone = '未填写座机' : '';
            $role = DB::table('crm_role_user as a')//join操作
                ->join('crm_roles as b','a.role_id','=','b.id')
                ->where('a.user_id',$v->uid)
                ->orderBy('b.id','desc')
                ->get();
            if($role){
                $display_name_str ='';
                foreach($role as $k => $roleValue){
                    if(($k+1) == count($role)){
                        $display_name_str  .= '['.$roleValue->display_name.']';
                    }else{
                        $display_name_str  .= '['.$roleValue->display_name.'],';
                    }
                }
                $display_name[$v->uid] = $display_name_str;
            }
        }

        return  Style::view('admin.crm_service.index',compact('userList','display_name', 'keyword'));
    }

    /**
     * 创建客服模版
     * @return mixed
     */
    public function create(){
        //查询角色
        $Role = DB::table('crm_roles')->get();
        //上班时间角色
        $CrmWorkRole = DB::table('crm_work_role')->get();
        return Style::view('admin.crm_service.create', compact('Role', 'CrmWorkRole'));
    }

    /**
     * 创建客服
     * @param Requests\admin\WebConfig\CrmUserCreate $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(Requests\admin\WebConfig\CrmUserCreate $request){
        $input =$request->only('name','worker_name','sex','birthday','phone','mobile','weichat','qq','email','enounce','work_role_id');
        $role = $request->only("role",'handleRole');
        $input['password'] = bcrypt($request->password);
        $input['created_at'] = date('Y-m-d H:i:s', time());
        $input['updated_at'] = date('Y-m-d H:i:s', time());

        $request->flash();

        if($ServiceUid = CrmService::insertGetId($input)){
            //添加选择的角色
            if(count($role['role']) > 0){
                foreach($role['role'] as $v){
                    if(!DB::table('crm_role_user')->where('user_id',$ServiceUid)->where("role_id",$v)->first() && $v!=0){
                        DB::table('crm_role_user')->insert(['user_id' => $ServiceUid, 'role_id' => $v]);
                    }
                }
            }
            $redirect = url("admin/workerhandle");
            $data = ['status'=>0,'msg'=>'用户【'.$input['worker_name'].'】创建成功'];
            $request->session()->flash('ok', json_encode($data));
        }else{
            $data = ['status'=>1,'msg'=>'创建失败'];
            $request->session()->flash('ok', json_encode($data));
            return back();
        }
        return redirect($redirect);
    }

    /**
     * 客服信息编辑
     * @param $uid
     * @return mixed
     */
    public function edit($uid){
        $userInfo = CrmService::where('uid', $uid)->firstOrFail();
        //查询角色
        $Role = DB::table('crm_roles')->get();
        //查看该用户已经绑定了什么角色
        $RoleUser = DB::table('crm_role_user')->where('user_id', $uid)->get();
        //上班时间角色
        $CrmWorkRole = DB::table('crm_work_role')->get();
        return Style::view('admin.crm_service.edit', compact('userInfo', 'Role', 'RoleUser', 'CrmWorkRole'));
    }

    /**
     * //修改客服资料
     * @param $uid
     * @param Requests\admin\WebConfig\CrmUserEdit $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update($uid,Requests\admin\WebConfig\CrmUserEdit $request){
        $input = $request->only('worker_name', 'sex', 'birthday', 'phone', 'mobile', 'weichat', 'qq', 'email', 'enounce');
        $role = $request->only('role', 'handleRole');
        $password = $request->only('password');
        if(!empty($password['password'])){
            $input['password'] = bcrypt($password['password']);
        }
        $input['updated_at'] = date('Y-m-d H:i:s', time());

        $request->flush();
        $userInfo = CrmService::where('uid',$uid)->firstOrFail();
        $userInfo->fill($input);
        $result = $userInfo->save();
        if ($result === false) {
            $data = ['status'=>1,'msg'=>'更新失败'];
            $request->session()->flash('ok', json_encode($data));
            return back();
        }
        if($role['handleRole'] == 1){
            //删除所有已有的角色
            DB::table('crm_role_user')->where('user_id',$uid)->delete();
            //添加选择的角色
            if(count($role['role']) > 0){
                foreach($role['role'] as $v){
                    if(!DB::table('crm_role_user')->where('user_id',$uid)->where("role_id",$v)->first() && $v!=0){
                        DB::table('crm_role_user')->insert(['user_id' => $uid, 'role_id' => $v]);
                    }
                }
            }
            $redirect = url("admin/workerhandle");
        }else{
            $redirect = "/admin/workerhandle/$uid/edit/";
        }

        $data = ['status'=>0,'msg'=>'员工信息更新成功'];
        $request->session()->flash('ok', json_encode($data));
        return redirect($redirect);
    }
    /**
     * 管理员删除员工账号
     * @param $uid
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($uid,Request $request){

        $request->only("name");
        if(CrmService::where("uid",$uid)->delete()){
            return response()->json(['status' => 0, 'msg' => "已成功删除[".$request->name."]"]);
        }else{
            return response()->json(['status' => 1, 'msg' => "操作失败，请稍后再试"]);
        }
    }

//    /**
//     * 头像上传
//     * @param Request $request
//     * @return \Illuminate\Http\JsonResponse
//     */
//    public function imgUpload(Request $request){
//
//        if ($request->hasFile('file')) {
//            $file=$request->file('file');
//            $entension = strtolower($file -> getClientOriginalExtension());
//            $mimeTye = $file -> getMimeType();
//            $clientName = $file -> getClientOriginalName();//客服端文件名
//            $size = $file ->  getSize();//文件大小
//
//            if ($file->isValid()) {
//
//                if (!in_array($entension, array('jpg', 'gif', 'png','jpeg'))){
//
//                    return response()->json(['error' => 304, 'info' => "文件类型只能为jpg、gif、png！"]);
//
//                }else {
//
//                    $fileurl = date("Ym") . '/';
//
//                    $filename = time() . strtolower(str_random(5)) . '.' . $entension;
//                    public_path() . '/upload/worker/' . $fileurl;
//
//                    $request->file('file')->move(public_path() . '/upload/worker/' . $fileurl, $filename);
//
//                    return response()->json(['status' => 200, 'url' => asset('upload/worker/'.$fileurl.$filename),'saveUrl'=>'/upload/worker/'.$fileurl.$filename]);
//
//                }
//            }
//
//        }else{
//            return response()->json(['error' => 306, 'info' => "没有选择上传图片文件！"]);
//        }
//    }
}
